package cn.zwx.security.example.security.handler;

import cn.hutool.core.collection.CollectionUtil;
import cn.zwx.security.example.common.resp.UserInfoResp;
import cn.zwx.security.example.config.JWTConfig;
import cn.zwx.security.example.entity.SysMenuEntity;
import cn.zwx.security.example.entity.extend.SelfUserEntity;
import cn.zwx.security.example.service.SelfUserDetailsService;
import cn.zwx.security.example.service.SysUserService;
import cn.zwx.security.example.utils.JWTTokenUtil;
import cn.zwx.security.example.utils.ResultUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @description 登录成功处理类
 * @author zhangwenxue
 * @createTime 2021/6/23 16:12
 **/
@Slf4j
@Component
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JWTConfig jwtConfig;
    @Autowired
    private JWTTokenUtil jwtTokenUtil;
    @Autowired
    private SysUserService sysUserService;

    /**
     * @description  登录成功返回结果
     * @return void
     * @author zhangwenxue
     * @createTime 2021/6/23 16:13
     **/
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication){
        // 组装JWT
        SelfUserEntity selfUserEntity =  (SelfUserEntity) authentication.getPrincipal();
        String token = jwtTokenUtil.createAccessToken(selfUserEntity);
        token = jwtConfig.getTokenPrefix() + token;
        // 封装返回参数
        // 用户菜单
        List<SysMenuEntity> sysMenuList = sysUserService.selectSysMenuByUserId(selfUserEntity.getUserId());
        UserInfoResp userInfoResp = JSON.parseObject(JSON.toJSONString(selfUserEntity), UserInfoResp.class);
        userInfoResp.setAuthorities(userInfoResp.getAuthorities());
        userInfoResp.setMenuEntityList(sysMenuList);
        // 用户角色
        userInfoResp.setAuthorities(selfUserEntity.getAuthorities());
        Map<String, Object> resultData = new HashMap<>();
        Map<String, Object> data = CollectionUtil.newHashMap();
        data.put("token",token);
        data.put("userInfo",userInfoResp);
        resultData.put("data",data);
        resultData.put("code","200");
        resultData.put("msg","请求成功!!");
        ResultUtil.responseJson(response,resultData);
    }


}